package cn.globalph.housekeeper.ui.task

import android.app.AlarmManager
import android.content.Context
import android.graphics.Bitmap
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.viewModelScope
import cn.globalph.housekeeper.BuildConfig
import cn.globalph.housekeeper.Event
import cn.globalph.housekeeper.HouseKeeperApplication
import cn.globalph.housekeeper.data.TokenStorage
import cn.globalph.housekeeper.data.model.BaseModel
import cn.globalph.housekeeper.data.model.Profile
import cn.globalph.housekeeper.data.model.ProfilesModel
import cn.globalph.housekeeper.data.model.Task
import cn.globalph.housekeeper.data.params.StartTaskParam
import cn.globalph.housekeeper.ui.BaseViewModel
import cn.globalph.housekeeper.utils.AlarmUtil
import cn.globalph.housekeeper.utils.TimeUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.lang.Exception
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

const val DATA_SHOW = "data_show"
const val DATA_EMPTY = "data_empty"
const val NET_ERROR = "net_error"

const val DIALOG_CHECK_CARD = 1
const val DIALOG_CUSTOM_SIGN = 2
class TaskViewModel(
    private val repository: TaskRepository
) : BaseViewModel() {
    private var _items = MutableLiveData<List<Task>>().apply {
        getData()
    }
    val items: LiveData<List<Task>> = _items

    private var _profiles = MutableLiveData<ProfilesModel>().apply { getProfiles() }
    val profiles: LiveData<ProfilesModel> = _profiles

    val showSwitch = Transformations.map(_profiles){
        var temp = false
        if(!it?.profiles.isNullOrEmpty()){
            temp = true
        }
        temp
    }

    var showProfiles = MutableLiveData<Event<Boolean>>()


    private val _dateStr = MutableLiveData<String>()
    val dateStr: LiveData<String> = _dateStr

    private val _dataChangeEvent = MutableLiveData<String>()
    val dateChangeEvent:LiveData<String> = _dataChangeEvent

    private val _startDialogEvent = MutableLiveData<Event<Int>>()
    val startDialogEvent:LiveData<Event<Int>> = _startDialogEvent

    private val _saveAlarmEvent = MutableLiveData<Event<String>>()
    val saveAlarmEvent:LiveData<Event<String>> = _saveAlarmEvent

    var showChooseEvent = MutableLiveData<Event<Boolean>>()
    var currentItem: Task? = null

    private val _itemDataChangeEvent = MutableLiveData<Event<Boolean>>()
    var itemDataChangeEvent:LiveData<Event<Boolean>> = _itemDataChangeEvent

    private val _refreshOverEvent = MutableLiveData<Event<Boolean>>()
    var refreshOverEven:LiveData<Event<Boolean>> = _refreshOverEvent

    private var calendar = Calendar.getInstance()
    private var nextDay = ""
    private var previewDay = ""
    private val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
    private var today = sdf.format(calendar.time)

    init {
        if(TokenStorage.token != null){
            Log.i("taskInit", TokenStorage.token!!)
        }
    }

    fun start() {
        showDate(0)
        nextDay = TimeUtil.getNextDay()
        previewDay = TimeUtil.getPreviewDay()
    }

    private fun getWeekDay(): String {
        var weekDay = calendar.get(Calendar.DAY_OF_WEEK)
        return when (weekDay) {
            1 -> "周日"
            2 -> "周一"
            3 -> "周二"
            4 -> "周三"
            5 -> "周四"
            6 -> "周五"
            7 -> "周六"
            else -> ""
        }
    }


    fun getData() {

        viewModelScope.launch {
            try {
                val model = repository.getDailyTasks(sdf.format(calendar.time))
                _items.value = model.data
                when {
                    model.isSuccessful() -> {
                        if(model.data.isNullOrEmpty()){
                            _dataChangeEvent.value = DATA_EMPTY
                        }else{
                            _dataChangeEvent.value = DATA_SHOW
                        }
                    }
                    model.isCertFail() -> _tokenEvent.value = Event(true)
                    else -> {
                        _toastEvent.value = Event(model.message)
                        _dataChangeEvent.value = DATA_EMPTY
                    }
                }
            } catch (e: Exception) {
                if (BuildConfig.DEBUG) e.printStackTrace()
                _toastEvent.value = Event("网络异常，请重试")
                _dataChangeEvent.value = NET_ERROR
            }
            _refreshOverEvent.value = Event(true)
        }
    }

    fun getProfiles() {
        viewModelScope.launch {
            try {
                val model = repository.getProfiles()
                when {
                    model.isSuccessful() -> {
                        _profiles.value = model.data
                    }
                    model.isCertFail() -> _tokenEvent.value = Event(true)
                    else -> _toastEvent.value = Event(model.message)
                }
            } catch (e: Exception) {
                if (BuildConfig.DEBUG) e.printStackTrace()
                _toastEvent.value = Event("网络异常，请重试")
            }
        }
    }

    fun itemClick(item: Task) {
        currentItem = item
        showChooseEvent.value = Event(true)
    }

    fun goNextDay() {
        val date = sdf.format(calendar.time)
        val hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY)
        if(date > today ||(date == today && hour<19)){
            _toastEvent.value = Event("暂无明天的排班")
            return
        }
        showDate(1)
        getData()
    }

    fun goPreviewDay() {
        showDate(-1)
        getData()
    }

    private fun showDate(deltaDay: Int) {
        val day = calendar.get(Calendar.DATE)
        calendar.set(Calendar.DATE, day + deltaDay)
        _dateStr.value = when (val tempDate = sdf.format(calendar.time)) {
            nextDay -> "明天（${getWeekDay()}）"
            today -> "今天（${getWeekDay()}）"
            previewDay -> "昨天（${getWeekDay()}）"
            else -> "$tempDate（${getWeekDay()}）"
        }
    }

    fun switchRole(i: Int) {
        viewModelScope.launch {
            val profile = profiles.value!!.profiles[i]
            try {
                val model =
                    repository.switchRole(profile.providerid.toString(), profile.roleid.toString())
                when {
                    model.isSuccessful() -> {
                        TokenStorage.token = model.data!!.token
                        TokenStorage.setUserData(
                            HouseKeeperApplication.instance.applicationContext,
                            model.data!!
                        )
                        getData()
                    }
                    model.isCertFail() -> _tokenEvent.value = Event(true)
                    else -> _toastEvent.value = Event(model.message)
                }
            } catch (e: Exception) {
                if (BuildConfig.DEBUG) e.printStackTrace()
                _toastEvent.value = Event("网络异常，请重试")
            }
        }
    }

    fun startService(context:Context) {
        viewModelScope.launch {
            try {
                val model = repository.startService(StartTaskParam(currentItem!!.id))
                when {
                    model.isSuccessful() ->{
                        _toastEvent.value = Event("服务开始")
                        if(model.data != null){
                            currentItem!!.actual_start_date = model.data!!.actualStartDate
                            _itemDataChangeEvent.value = Event(true)
                        }
                        val time:Long = ((currentItem!!.order_duration.toDouble()-1/6.toDouble())*60*60*1000+System.currentTimeMillis()).toLong()
//                        val time:Long = (currentItem!!.order_duration.toDouble()*10*1000+System.currentTimeMillis()).toLong()
                        _saveAlarmEvent.value = Event("${currentItem!!.id} $time")
                        AlarmUtil.startAlarm(
                            context,
                            currentItem!!.id.toInt(),
                            time,
                            "MY_ALARM"
                        )
                    }
                    model.isCertFail() -> _tokenEvent.value = Event(true)
                    else -> _toastEvent.value = Event(model.message)
                }
            } catch (e: Exception) {
                if (BuildConfig.DEBUG) e.printStackTrace()
                _toastEvent.value = Event("网络异常，请重试")
            }
        }
    }

    fun getCustomSignToken(context: Context,btimap:Bitmap){
        viewModelScope.launch {
            try {
                if(currentItem == null) return@launch
                val model = repository.getCustomSignToken(currentItem!!.id,"用户签名",btimap)
                when {
                    model.isSuccessful() -> {
                        currentItem?.let {
                            if(model.data != null){
                                it.actual_end_date = model.data!!.actualEndDate
                                it.status = model.data!!.status
                                _itemDataChangeEvent.value = Event(true)
                            }
                            AlarmUtil.cancelAlarm(
                                context,
                                currentItem!!.id.toInt(),
                                "MY_ALARM"
                            )
                        }
                        _toastEvent.value = Event("签名上传成功")
                    }
                    model.isCertFail() -> _tokenEvent.value = Event(true)
                    else -> _toastEvent.value = Event(model.message)
                }
            }catch (e:Exception){
                if(BuildConfig.DEBUG) e.printStackTrace()
                _toastEvent.value = Event("网络异常，请重试")
            }
        }
    }

    fun getDate():String{
        return sdf.format(calendar.time)
    }

    fun checkSignDialogShow(){
        currentItem?.let {
            if(it.actual_start_date == null){
                _toastEvent.value = Event("请先开始服务！")
                return
            }
            if(!it.actual_end_date.isNullOrEmpty()){
                _toastEvent.value = Event("本次服务已存在用户签名！")
                return
            }
            if(!it.hasCheck){
                viewModelScope.launch {
                    val model = repository.getCheckInfo(currentItem!!.id)
                    when{
                        model.isSuccessful()->{
                            if(!model.data.isNullOrEmpty())
                                currentItem!!.hasCheck = true
                        }
                        model.isCertFail()->{
                            _tokenEvent.value = Event(true)
                            return@launch
                        }
                        else->{}
                    }

                    if(it.hasCheck){
                        _startDialogEvent.value = Event(DIALOG_CUSTOM_SIGN)
                    }else{
                        _toastEvent.value = Event("请先填写检查卡")
                        _startDialogEvent.value = Event(DIALOG_CHECK_CARD)
                    }
                }
            }else{
                _startDialogEvent.value = Event(DIALOG_CUSTOM_SIGN)
            }
        }

    }
}